﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace itChatAdmin
{
    public class AppConfig
    {
        public static string KEY_64 = "S8xJsys6";
        public static string IV_64 = "s2JysG6j";
        
        ///<summary> 
        ///更新AppSetting字符串  
        ///</summary> 
        ///<param name="AppSettingKey">AppSettingKey</param> 
        ///<param name="AppValueString">AppValueString</param> 
        public static void SetAppSettingKeyValue(string AppSettingKey, string AppValueString)
        {
            bool isModified = false;
            // 打开可执行的配置文件*.exe.config  
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (config.AppSettings.Settings[AppSettingKey] != null)
            {
                isModified = true;
            }


            // 如果连接串已存在，首先删除它
            if (isModified)
            {
                config.AppSettings.Settings.Remove(AppSettingKey);
            }

            WebValidate Wv = new WebValidate();
            String myValue = Wv.Encode(AppValueString, KEY_64, IV_64);
            //添加配置信息
            config.AppSettings.Settings.Add(AppSettingKey, myValue);

            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);

            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("AppSettings");
        }

        public static String GetAppSettingValue(string AppSettingKey)
        {
            WebValidate Wv = new WebValidate();
            // 打开可执行的配置文件*.exe.config  
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[AppSettingKey] != null)
            {
                return Wv.Decode(config.AppSettings.Settings[AppSettingKey].Value, KEY_64, IV_64);
            }

            //未找到，添加配置

            //添加配置信息
            config.AppSettings.Settings.Add(AppSettingKey, Wv.Encode("", KEY_64, IV_64));

            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);

            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("AppSettings");

            return "";
        }

        
    }
    public class WebValidate
    {
        string KEY_64 = "S8xJsys6";
        string IV_64 = "s2JysG6j";
        volatile string NEW_KEY_64 = "";
        volatile string NEW_IV_64 = "";

        public String ValidateOrder(String ThisAppID, String OrderID, String Phone)
        {
            //注册表中有数据，网络验证
            #region 获取密钥对
            HttpClientHandler hander = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                UseCookies = true
            };
            HttpClient httpClient = new HttpClient(hander);
            httpClient.MaxResponseContentBufferSize = 256000;
            String url = "http://Api.WeiShangTools.com/CheckRegister.aspx";
            var responseC = httpClient.GetAsync(url).Result;
            String resultC = responseC.Content.ReadAsStringAsync().Result;
            string KeyIV = Decode(resultC, KEY_64, IV_64);
            var KeyIVJson = JObject.Parse(KeyIV);
            NEW_KEY_64 = KeyIVJson["KEY"].ToString();
            NEW_IV_64 = KeyIVJson["IV"].ToString();
            #endregion

            #region 加密上传字符字符串
            var paramList1 = new Dictionary<string, string>()
            {
                {"Phone", Encode(Phone)},
                {"AppID", Encode(ThisAppID)},
                {"OrderID", Encode(OrderID)}
            };
            var responseB = httpClient.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList1)).Result;
            String resultB = responseB.Content.ReadAsStringAsync().Result;
            string Result = Decode(resultB);
            httpClient.Dispose();
            return Result;
            #endregion
        }
        string Encode(string data)
        {
            return Encode(data, NEW_KEY_64, NEW_IV_64);
        }

        public string Encode(string data, string key_64, String iv_64)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }
        string Decode(string data)
        {
            return Decode(data, NEW_KEY_64, NEW_IV_64);
        }

        public string Decode(string data, string key_64, String iv_64)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
    }
}
